package com.xy.controller;

import com.xy.api.exception.AuthorizationException;
import com.xy.api.exception.BizException;
import com.xy.api.model.response.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;


@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    private static final int FAIL_CODE = 500;

    private static final int AUTHORIZATION_CODE = 401;

    private static final String FAIL_MSG = "操作失败";

    @ExceptionHandler(value = BizException.class)
    public R bizException(HttpServletRequest request, BizException ex) {
        log.error("BizException", ex);
        return new R(FAIL_CODE, ex.getMessage(), null);
    }

    @ExceptionHandler(value = AuthorizationException.class)
    public R authorizationException(HttpServletRequest request, AuthorizationException ex) {
        log.error("AuthorizationException", ex);
        return new R(AUTHORIZATION_CODE, FAIL_MSG, null);
    }

    @ExceptionHandler(value = Exception.class)
    public R exceptionHandler(HttpServletRequest request, Exception ex) {
        log.error("Exception", ex);
        return new R(FAIL_CODE, FAIL_MSG, null);
    }
}
